package orm

import (
	"fmt"
	"os"
	"sync"

	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"

	"im/model"
)

var (
	instance *xorm.Engine
	once     sync.Once
)

func GetDB() *xorm.Engine {

	once.Do(func() {
		host := os.Getenv("DB_HOST")
		port := os.Getenv("DB_PORT")
		database := os.Getenv("DB_DATABASE")
		username := os.Getenv("DB_USERNAME")
		password := os.Getenv("DB_PASSWORD")
		charset := os.Getenv("DB_CHARSET")
		db_config := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s", username, password, host, port, database, charset)
		var err error
		db, err := xorm.NewEngine("mysql", db_config)
		if err != nil {

			panic("数据库连接失败")
		}
		if os.Getenv("APP_DEBUG") == "true" {
			db.ShowSQL(true)
		}
		instance = db
	})
	return instance
}

// 数据库结构同步方法
func SyncDB() {
	db := GetDB()
	err := db.Sync2(
		new(model.Apps),
		new(model.Groups),
		new(model.GroupsUsers),
		new(model.Classes),
		new(model.PrivateMessages),
		new(model.Users),
		new(model.UsersFriends),
		new(model.GroupsMessages),
		new(model.Attachments),
		new(model.Collections),
		new(model.Posts),
		new(model.Replys),
		new(model.InternalMails),
		new(model.Likes),
		new(model.Channels),
		new(model.PushLog),
		new(model.SystemConfigs),
		new(model.EsJobs),
	)
	if err != nil {
		panic("数据库结构同步失败 原因:" + err.Error())
	}
}
